package com.ilarele.shopping.client.util;

import java.io.File;
import java.io.IOException;
import java.util.Random;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.EmptyDialogListener;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.facebook.android.SessionStore;
import com.ilarele.shopping.client.R;

public class Global {

	public static final String SERVER_IP = "10.38.131.125";// cs

	// public static final String SERVER_IP = "10.0.2.2"; // emulator
	// public static final String SERVER_IP = "10.30.255.161"; // rectorat
	public static final int PORT = 9999;
	public static final int IMAGE_SEND_PORT = 8888;
	public static final int IMAGE_GET_PORT = 7777;
	public static final String SERVER_IMAGE_IP = SERVER_IP;

	public static final double DEFAULT_LONGITUDE = 0;
	public static final double DEFAULT_LATITUDE = 0;

	public static String clientId;
	public static String clientName;
	public static String clientEmail;
	public static boolean isPublic;

	// public static ArrayList<Product> newInsertedItems = new
	// ArrayList<Product>();
	public static SharedPreferences pref;
	public static Editor editor;
	public static Random rand = new Random();

	public static final CharSequence SORT_DATE = "Date";
	public static final CharSequence SORT_LOCATION = "Location";
	public static final CharSequence SORT_PRICE = "Price";

	public static final int SORT_DATE_INDEX = 0;
	public static final int SORT_LOCATION_INDEX = SORT_DATE_INDEX + 1;
	public static final int SORT_PRICE_INDEX = SORT_LOCATION_INDEX + 1;

	// flurry
	public static final String FLURRY_ID = "JQ48A948TWALKZ32LND1";

	// facebook
	private static final String FACEBOOK_APP_ID = "215496371823936";
	private static final String APP_SITE = "http://code.google.com/p/social-shopping-adviser/";

	public static final boolean DEBUG_MODE = true;

	public static Facebook facebook = null;
	public static AsyncFacebookRunner asyncRunner = null;

	public static File DEFAULT_PICTURES_DIRECTORY = new File(Environment
			.getExternalStorageDirectory().getAbsolutePath()
			+ "/"
			+ "Pictures/");
	public static File SHOPPING_PICTURES_DIRECTORY = new File(
			DEFAULT_PICTURES_DIRECTORY, "shopping");
	private static Boolean dbCleared = false;

	public static void initGlobal(Activity activity) {
		if (!SHOPPING_PICTURES_DIRECTORY.exists()) {
			SHOPPING_PICTURES_DIRECTORY.mkdirs();
			try {
				new File(SHOPPING_PICTURES_DIRECTORY.getAbsolutePath(),
						".nomedia").createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		pref = PreferenceManager.getDefaultSharedPreferences(activity);
		TelephonyManager telephony = (TelephonyManager) activity
				.getSystemService(Context.TELEPHONY_SERVICE);

		editor = pref.edit();
		clientId = telephony.getDeviceId();
		clientId = "testLic2"; // TODO: comment this line
		System.out.println("telephony.getDeviceId()" + telephony.getDeviceId());

		clientName = pref.getString("name", "ilarele");
		clientEmail = pref.getString("email", "none@gmail.com");
		isPublic = pref.getBoolean("private", true);
		facebook = new Facebook(FACEBOOK_APP_ID);
		asyncRunner = new AsyncFacebookRunner(facebook);
		silentFacebook(facebook, activity);

	}

	public static String getImgUrl(String imageUrl) {
		return "http://" + SERVER_IMAGE_IP + "/" + imageUrl;
	}

	public static String getPicPath(String imgName) {
		return SHOPPING_PICTURES_DIRECTORY + "/" + imgName;
	}

	public static boolean isConnectedToInternet(Context ctx) {
		ConnectivityManager cm = (ConnectivityManager) ctx
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (cm.getActiveNetworkInfo() != null)
			return true;
		return false;
	}

	// facebook
	private static void silentFacebook(final Facebook fb,
			final Activity activity) {
		SessionStore.restore(fb, activity);
		if (!fb.isSessionValid()) {
			activity.runOnUiThread(new Runnable() {
				@Override
				public void run() {
					fb.authorize(activity, new String[] { "publish_stream" },
							new SimpleDialogListener(activity));
				}
			});
		}
	}

	public static void postOnFacebook(final Activity activity, String message) {
		if (!facebook.isSessionValid()) {
			activity.runOnUiThread(new Runnable() {
				@Override
				public void run() {
					facebook.authorize(activity,
							new String[] { "publish_stream" },
							new SimpleDialogListener(activity));
				}
			});
		}
		Bundle parameters = new Bundle();
		parameters.putString("message", message);
		parameters.putString("name", activity.getString(R.string.app_name));
		parameters.putString("link", APP_SITE);
		parameters.putString("description",
				activity.getString(R.string.facebook_message));

		try {
			facebook.dialog(activity, "feed", parameters,
					new EmptyDialogListener());
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	// Uses the mobile-specific version of Product Search, which is formatted
	// for small screens.
	public static final void openProductSearch(String upc, Activity parent) {
		Uri uri = Uri.parse("http://www.google.com/m/products?q=" + upc
				+ "&source=zxing");
		System.out.println(uri.getPath());
		launchIntent(new Intent(Intent.ACTION_VIEW, uri), parent);
	}

	public static final void launchIntent(Intent intent, Activity parent) {
		if (intent != null) {
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
			try {
				parent.startActivity(intent);
			} catch (ActivityNotFoundException e) {
				AlertDialog.Builder builder = new AlertDialog.Builder(parent);
				builder.setTitle(R.string.app_name);
				builder.setMessage(R.string.msg_intent_failed);
				builder.setPositiveButton(R.string.button_ok, null);
				builder.show();
			}
		}
	}

	public static boolean dbWasCleared() {
		synchronized (dbCleared) {
			if (dbCleared) {
				dbCleared = false;
				return true;
			}
			return false;
		}
	}

	public static void setDbCleared() {
		synchronized (dbCleared) {
			dbCleared = true;
		}
	}
}

class SimpleDialogListener implements DialogListener {

	private Context mContext;

	public SimpleDialogListener(Context ctx) {
		mContext = ctx;
	}

	@Override
	public void onComplete(Bundle values) {
		final String postId = values.getString("post_id");
		SessionStore.save(Global.facebook, mContext);
		if (postId != null) {
			Log.d("Facebook-Example", "Dialog Success! post_id=" + postId);
		} else {
			Log.d("Facebook-Example", "No wall post made");
		}
	}

	@Override
	public void onFacebookError(FacebookError e) {
	}

	@Override
	public void onError(DialogError e) {
	}

	@Override
	public void onCancel() {
	}
}
